<template>
  <div class="search">
    <Card>
      <Row>
        <Form ref="editForm" :model="editForm" :rules="rules" :label-width="100">
          <FormItem label="场地名称" prop="siteName" style="width: 100%">
            <Input
              v-model="editForm.siteName"
              maxlength="11"
              placeholder="请输入场地名称"
            />
          </FormItem>
          <FormItem label="场地照片" style="width: 100%">
            <Upload
              action
              type="drag"
              ref="upload"
              :max-size="2 * 1024"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              accept=".jpg, .jpeg, .bmp, .png"
              :format="['jpg', 'jpeg', 'bmp', 'png']"
              style="width: max-content; display: inline-block"
            >
              <img v-if="editForm.siteCover" :src="editForm.siteCover" height="150" />
              <div v-else style="width: 150px; height: 150px; line-height: 150px">
                <Icon type="md-add" size="20" />
              </div>
            </Upload>
            <span style="margin-left: 20px; color: #aaa"
              >只能上传jpg/png/bmp文件，且不超过2MB</span
            >
          </FormItem>
          <FormItem label="场地地址" prop="addressId" style="width: 100%">
            <Cascader
              :data="regionList"
              v-model="editForm.addressId"
              :load-data="loadData"
              @on-change="changeRegion"
            ></Cascader>
          </FormItem>
          <FormItem label="详细地址" prop="siteAddress" style="width: 100%">
            <Input v-model="editForm.siteAddress" placeholder="请输入详细地址" />
          </FormItem>
          <FormItem label="场地详情" prop="siteDetail" style="width: 100%">
            <editor
              ref="editor"
              openXss
              v-model="editForm.siteDetail"
              :init="{ ...initEditor, height: '800px' }"
            ></editor>
          </FormItem>
          <FormItem label="场地工作室数" prop="numberOfRooms" style="width: 100%">
            <InputNumber
              v-model="editForm.numberOfRooms"
              placeholder="请输入场地工作室数"
              style="width: 100%"
            ></InputNumber>
          </FormItem>
          <div>
            <Button type="text" @click="toback">返回</Button>
            <Button type="primary" @click="submitForm">保存</Button>
          </div>
        </Form>
      </Row>
    </Card>
  </div>
</template>

<script>
import * as API_Yard from "@/api/yard.js";
import * as API_Index from "@/api/index.js";

import Editor from "@tinymce/tinymce-vue";
import { initEditor } from "@/components/editor/config";

export default {
  name: "yard-form",
  components: {
    editor: Editor,
  },
  data() {
    return {
      initEditor: initEditor,
      editForm: {}, // 表单
      regionList: [], //省市县列表
      rules: {
        // 验证规则
        siteName: [{ required: true, message: "请输入场地名称" }],
        siteCover: [{ required: true, message: "请上传场地照片" }],
        addressId: [{ required: true, message: "请选择场地地址" }],
        siteAddress: [{ required: true, message: "请输入详细地址" }],
        siteDetail: [{ required: true, message: "请输入场地详情" }],
        numberOfRooms: [{ required: true, message: "请输入场地工作室数" }],
      },
    };
  },
  mounted() {
    this.getregionList();
    let id = this.$route.query.id;
    this.init(id);
  },
  methods: {
    // 返回上级
    toback() {
      this.$store.commit("removeTag", "yard-form");
      localStorage.pageOpenedList = JSON.stringify(this.$store.state.app.pageOpenedList);
      this.$router.go(-1);
    },
    // 初始化表单
    init(id) {
      this.$refs.editForm.resetFields();
      let form = {
        id: null,
        siteName: null, //场地名称
        siteCover: null, //场地封面
        addressId: [], //场地地址ID（仅页面使用）
        regionId: null, //场地地址ID
        region: null, //场地地址名称
        siteAddress: null, //详细地址
        siteDetail: null, //场地详情
        numberOfRooms: null, //场地工作室数
        daysOpen: 1, //开放天数
      };
      if (id) {
        API_Yard.getYardDetail(id).then((res) => {
          if (res.success) {
            this.editForm = Object.assign(form, res.result);
            this.editForm.addressId = res.result.regionId.split(",");
          }
        });
      } else {
        this.editForm = Object.assign({}, form);
      }
    },
    // 自定义上传
    beforeUpload(file) {
      let typeList = [".jpg", ".jpeg", ".bmp", ".png"];
      if (!typeList.some((i) => file.name.lastIndexOf(i) != -1)) {
        this.$Message.warning("请检查上传文件格式");
        return;
      }
      if (file.size / 1024 > 2 * 1024) {
        this.$Message.warning("图片大小不能超过2MB");
        return;
      }
      const formData = new FormData();
      formData.append("file", file);
      API_Yard.postUpload(formData).then((res) => {
        if (res.success) {
          this.editForm.siteCover = res.result;
        }
      });
      return false;
    },
    // 选择省-市
    changeRegion(val, list) {
      // 地址ID
      this.editForm.regionId = list
        .map((i) => {
          return i.value;
        })
        .join(",");
      // 地址中文
      this.editForm.region = list
        .map((i) => {
          return i.label;
        })
        .join(",");
      // 详细地址中文
      this.editForm.siteAddress = list
        .map((i) => {
          return i.label;
        })
        .join("");
    },
    //提交
    submitForm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          let form = Object.assign(this.editForm, {});
          delete form.addressId;
          API_Yard.postYardSave(form).then((res) => {
            if (res.success) {
              this.$Message.success(form.id ? "修改成功" : "添加成功");
              this.toback();
            }
          });
        }
      });
    },
    // 获取省-市列表
    getregionList() {
      API_Index.getAllCity().then((res) => {
        if (res.result) {
          this.regionList = this.filterAddress(res.result, "city");
        }
      });
    },
    // 处理省-市/区县字段
    filterAddress(data, key) {
      let list = [];
      data.forEach((item) => {
        let obj = {
          label: item.name,
          value: item.id,
        };
        if (key == "city") {
          obj.children = this.filterAddress(item.children, key);
          obj.loading = false;
        }
        list.push(obj);
      });
      return list;
    },
    // 动态加载区县
    loadData(item, callback) {
      item.loading = true;
      API_Index.getCityChild(item.value)
        .then((res) => {
          if (res.result) {
            item.children = this.filterAddress(res.result, "county");
          }
        })
        .finally(() => {
          item.loading = false;
          callback();
        });
    },
  },
};
</script>
<style lang="scss" scoped></style>
